<template>
  <div class="app-container">
    <!-- 搜索 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleAdd">+ 添加</el-button>
      <div class="filters">
        <el-select v-model="queryParams.organization" placeholder="组织结构" class="filter-item" clearable>
          <el-option label="信息工程学院" value="信息工程学院" />
          <el-option label="人工智能学院" value="人工智能学院" />
          <el-option label="土木工程学院" value="土木工程学院" />
        </el-select>
        <el-input v-model="queryParams.name" placeholder="请输入姓名" class="filter-item" clearable />
        <el-input v-model="queryParams.account" placeholder="请输入账号" class="filter-item" clearable />
        <el-select v-model="queryParams.warningLevel" placeholder="预警级别" class="filter-item" clearable>
          <el-option
              v-for="item in warningLevelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
        <el-select v-model="queryParams.source" placeholder="预警来源" class="filter-item" clearable>
          <el-option
              v-for="item in sourceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
        <div class="filter-actions">
          <el-button icon="Search" type="primary" @click="handleQuery">查询</el-button>
          <el-button icon="Remove" @click="resetQuery">重置</el-button>
          <el-button type="primary" icon="Download" @click="handleExport">导出</el-button>
        </div>
      </div>
    </div>

    <!-- 表格 -->
    <div class="table-box">
      <el-table :data="tableData" style="width: 100%" :header-cell-style="{ 'background-color': '#f5f7fa' }">
        <el-table-column prop="warningTime" min-width="140" label="预警时间" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="account" label="账号" />
        <el-table-column prop="organization" label="组织结构" />
        <el-table-column prop="warningLevel" label="预警级别">
          <template #default="{ row }">
            <span class="status-dot" :class="getWarningLevelClass(row.warningLevel)"></span>
            <span class="status-text">{{ row.warningLevel }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="预警来源" />
        <el-table-column prop="lastModified" min-width="100" label="操作时间" />
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <span class="blue-action" @click="handleView(scope.row)">查看</span>
            <span class="blue-action" @click="handleEdit(scope.row)">编辑</span>
            <span class="red-action" @click="handleDelete(scope.row)">删除</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog title="增加预警" v-model="dialogVisible" width="700px" :close-on-click-modal="false" @close="resetAddForm">
      <el-form :model="form" :rules="rules" ref="addFormRef" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="预警级别" prop="warningLevel">
          <el-select v-model="form.warningLevel" placeholder="请选择预警级别">
            <el-option v-for="item in warningLevelOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="预警来源" prop="source">
          <el-select v-model="form.source" placeholder="请选择预警来源">
            <el-option v-for="item in sourceOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="预警时间" prop="warningTime">
          <el-date-picker 
            v-model="form.warningTime" 
            type="datetime" 
            placeholder="选择日期时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
          />
        </el-form-item>
        <el-form-item label="备注" prop="details">
          <el-input type="textarea" v-model="form.details" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看/编辑详情对话框 -->
    <el-dialog v-model="detailDialogVisible" :title="dialogMode==='view'?'查看预警记录':'编辑预警记录'" width="700px">
      <el-form ref="detailFormRef" :model="detailForm" :rules="detailRules" label-width="100px">
        
        <!-- 姓名 -->
        <el-form-item label="姓名" prop="name" required>
          <el-input v-if="dialogMode==='edit'" v-model="detailForm.name" />
          <span v-else>{{ detailForm.name }}</span>
        </el-form-item>

        <!-- 预警级别 -->
        <el-form-item label="预警级别" prop="warningLevel" required>
          <el-select v-if="dialogMode==='edit'" v-model="detailForm.warningLevel" placeholder="请选择预警级别">
            <el-option v-for="item in warningLevelOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <span v-else>{{ detailForm.warningLevel }}</span>
        </el-form-item>

        <!-- 预警来源 -->
        <el-form-item label="预警来源" prop="source" required>
          <el-select v-if="dialogMode==='edit'" v-model="detailForm.source" placeholder="请选择预警来源">
            <el-option v-for="item in sourceOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <span v-else>{{ detailForm.source }}</span>
        </el-form-item>

        <!-- 预警时间 -->
        <el-form-item label="预警时间" prop="warningTime" required>
          <el-date-picker v-if="dialogMode==='edit'"
            v-model="detailForm.warningTime" 
            type="datetime" 
            placeholder="选择日期时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
          />
          <span v-else>{{ detailForm.warningTime }}</span>
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注">
          <el-input v-if="dialogMode==='edit'" type="textarea" v-model="detailForm.details" :rows="3" />
          <span v-else>{{ detailForm.details }}</span>
        </el-form-item>

      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button v-if="dialogMode==='edit'" @click="resetDetailForm">重置</el-button>
          <el-button v-if="dialogMode==='edit'" type="primary" @click="handleSaveDetail">保存修改</el-button>
          <el-button v-if="dialogMode==='view'" @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import { ElMessage, ElMessageBox } from 'element-plus';

const queryForm = ref(null);
const queryParams = reactive({
  name: '',
  account: '',
  organization: '',
  source: '',
  warningLevel: '',
});


const treeData = ref([
  {
    value: '1',
    label: '院系',
    children: [
      {
        value: '1-1',
        label: '软件学院',
      },
    ],
  },
]);

const treeProps = {
  children: 'children',
  label: 'label',
};

const sourceOptions = ref([
  { value: '管理员添加', label: '管理员添加' },
  { value: '个体评测', label: '个体评测' },
  { value: '团体评测', label: '团体评测' },
  { value: '用户端自测', label: '用户端自测' },
]);

const warningLevelOptions = ref([
  { value: '正常适应', label: '正常适应' },
  { value: '轻度关注', label: '轻度关注' },
  { value: '重点关注', label: '重点关注' },
  { value: '高度风险', label: '高度风险' },
  { value: '危机状态', label: '危机状态' },
]);

const initialTableData = ref([
  {
    name: '李明',
    account: '20250001',
    organization: '软件学院',
    warningLevel: '危机状态',
    source: '管理员添加',
    warningTime: '2025-03-21 11:18',
    lastModified: '2025-03-21 14:30',
  },
  {
    name: '王浩然',
    account: '20250002',
    organization: '软件学院',
    warningLevel: '高度风险',
    source: '个体评测',
    warningTime: '2025-03-21 09:45',
    lastModified: '2025-03-21 16:20',
  },
  {
    name: '周子航',
    account: '20250003',
    organization: '软件学院',
    warningLevel: '正常适应',
    source: '用户端自测',
    warningTime: '2025-03-21 15:30',
    lastModified: '2025-03-21 10:15',
  },
]);

const tableData = ref([...initialTableData.value]);

const addFormRef = ref(null);
const dialogVisible = ref(false);
const detailDialogVisible = ref(false);
const dialogMode = ref('view');
const detailFormRef = ref(null);
const detailForm = ref({
  id: null,
  name: '',
  warningLevel: '',
  source: '',
  warningTime: '',
  details: ''
});

const form = reactive({
  name: '',
  source: '',
  warningLevel: '',
  warningTime: '',
  details: '',
});

const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  warningLevel: [{ required: true, message: '请选择预警级别', trigger: 'change' }],
  source: [{ required: true, message: '请选择预警来源', trigger: 'change' }],
  warningTime: [{ required: true, message: '请选择预警时间', trigger: 'change' }],
  // 备注改为非必填项
  details: [{ required: false, message: '请输入预警情况', trigger: 'blur' }],
};

const detailRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  warningLevel: [{ required: true, message: '请选择预警级别', trigger: 'change' }],
  source: [{ required: true, message: '请选择预警来源', trigger: 'change' }],
  warningTime: [{ required: true, message: '请选择预警时间', trigger: 'change' }]
};

onMounted(() => {
  const storedData = sessionStorage.getItem('warningTableData');
  if (storedData) {
    const parsedData = JSON.parse(storedData);
    initialTableData.value = parsedData;
    tableData.value = parsedData;
  }
});

watch(initialTableData, (newData) => {
  sessionStorage.setItem('warningTableData', JSON.stringify(newData));
}, { deep: true });


const handleAdd = () => {
  resetAddForm();
  dialogVisible.value = true;
};

const handleView = (row) => {
  dialogMode.value = 'view';
  detailForm.value = { 
    ...row, 
    details: '无',  // 预警情况为"无"
    warningLevel: '危机状态',  // 预警级别为"危机状态"
    source: '管理员添加'  // 预警来源为"管理员添加"
  };
  detailDialogVisible.value = true;
};

const handleEdit = (row) => {
  dialogMode.value = 'edit';
  detailForm.value = { 
    ...row,
    details: row.details || ''
  };
  detailDialogVisible.value = true;
};

const handleExport = () => {
  // 准备导出数据，不包含评估记录和预警报告等操作按钮列
  const exportData = tableData.value.map(item => ({
    姓名: item.name,
    账号: item.account,
    组织结构: item.organization,
    预警级别: item.warningLevel,
    预警来源: item.source,
    预警时间: item.warningTime
  }));

  // 创建工作簿
  const workbook = XLSX.utils.book_new();
  const worksheet = XLSX.utils.json_to_sheet(exportData);

  // 添加工作表到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, '预警列表');

  // 生成Excel文件并下载
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
  const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
  saveAs(blob, `预警列表_${new Date().toLocaleDateString()}.xlsx`);
};

const handleQuery = () => {
  let filteredData = [...initialTableData.value];

  if (queryParams.name) {
    filteredData = filteredData.filter(item => item.name.includes(queryParams.name));
  }
  if (queryParams.account) {
    filteredData = filteredData.filter(item => item.account.includes(queryParams.account));
  }
  if (queryParams.organization) {
    filteredData = filteredData.filter(item => item.organization === queryParams.organization);
  }
  if (queryParams.source) {
    filteredData = filteredData.filter(item => item.source === queryParams.source);
  }
  if (queryParams.warningLevel) {
    filteredData = filteredData.filter(item => item.warningLevel === queryParams.warningLevel);
  }

  tableData.value = filteredData;
};

const resetQuery = () => {
  if (queryForm.value) {
    queryForm.value.resetFields();
  }
  queryParams.name = '';
  queryParams.account = '';
  queryParams.organization = '';
  queryParams.source = '';
  queryParams.warningLevel = '';
  tableData.value = [...initialTableData.value];
};

const submitForm = () => {
  if (!addFormRef.value) return;
  addFormRef.value.validate((valid) => {
    if (valid) {
      const newEntry = {
        ...form,
        organization: '软件学院', // Default organization
        warningTime: form.warningTime, // 保持原始格式 YYYY-MM-DD HH:mm
        account: 'test' + Math.floor(Math.random() * 1000), // Placeholder account
        interventionLevel: '', // 干预级别设为空
        lastModified: new Date().toLocaleString('zh-CN', { 
          year: 'numeric', 
          month: '2-digit', 
          day: '2-digit', 
          hour: '2-digit', 
          minute: '2-digit' 
        }).replace(/\//g, '-'), // 添加当前时间为操作时间
      };
      initialTableData.value.unshift(newEntry);
      tableData.value.unshift(newEntry);
      dialogVisible.value = false;
    }
  });
};

const resetAddForm = () => {
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
  form.name = '';
  form.source = '';
  form.warningLevel = '';
  form.warningTime = '';
  form.details = '';
};

const resetDetailForm = () => {
  if (detailFormRef.value) {
    detailFormRef.value.resetFields();
  }
};

const handleSaveDetail = () => {
  if (!detailFormRef.value) return;
  
  detailFormRef.value.validate((valid) => {
    if (valid) {
      const index = tableData.value.findIndex(item => item.name === detailForm.value.name);
      if (index !== -1) {
        tableData.value[index] = { ...detailForm.value };
        
        // 同时更新初始数据
        const initialIndex = initialTableData.value.findIndex(item => item.name === detailForm.value.name);
        if (initialIndex !== -1) {
          initialTableData.value[initialIndex] = { ...detailForm.value };
        }
        
        ElMessage.success('保存成功');
        detailDialogVisible.value = false;
      }
    }
  });
};

const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该条记录吗?',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const index = initialTableData.value.findIndex(item => item.name === row.name);
    if (index !== -1) {
      initialTableData.value.splice(index, 1);
      tableData.value = [...initialTableData.value];
    }
    ElMessage({
      type: 'success',
      message: '删除成功',
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除',
    });
  });
};

const getWarningLevelClass = (level) => {
  switch (level) {
    case '危机状态':
      return 'status-high';
    case '高度风险':
      return 'status-medium';
    case '正常适应':
      return 'status-low';
    default:
      return '';
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

:deep(.el-table) {
  border: none;
  box-shadow: none;
}

/* 统一的搜索栏样式 */
.action-bar {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
}

.filters {
  display: flex;
  flex-wrap: wrap;
  margin-left: 20px;
  gap: 12px;
}

.filter-item {
  width: 200px;
}

.filter-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.table-box {
  margin-bottom: 20px;
}

/* 操作按钮样式 */
.blue-action {
  color: #409EFF;
  margin-right: 12px;
  cursor: pointer;
  user-select: none;
}

.red-action {
  color: #F56C6C;
  margin-right: 12px;
  cursor: pointer;
  user-select: none;
}

.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 8px;
}

.status-text {
  font-weight: bold;
}

.status-high {
  background-color: red;
}

.status-medium {
  background-color: orange;
}

.status-low {
  background-color: green;
}

/* 必填字段标识 */
:deep(.el-form-item.is-required .el-form-item__label:before) {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}
</style>
